/*
 * 文件说明: Ajax代理
 * @author: 无所谓 yagqfhd@qq.com
 * @since: 2023-12-20
 * @file: request.ts
 * @version: 0.0.1
 * 
 **/

import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from "axios"
import { useAuthStoreHook } from "@/store/auth"

// 创建 axios 实例
const service = axios.create({
    baseURL: `/`,
    timeout: 50000,
    headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        
        const appStore = useAuthStoreHook();
        // console.log(appStore.hasToke, appStore.token)
        if (appStore.hasToken) {
            config.headers.Authorization = appStore.token?.access_token;
        }
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        // console.log('request', response)
        const { status } = response.data;
        if (status === 0) {
            return response.data;
        }
        // 响应数据为二进制流处理(Excel导出)
        const responseType = response.request?.responseType
        if (responseType === "blob" || responseType === "arraybuffer") return response.data
        return Promise.reject(new Error("非本系统的接口"))
    },
    (error: any) => {
        console.log(error, typeof error)
        // if (error.response.data) {
        //     // const { status } = error.response.data;
        //     // token 过期,重新登录
        //     // if (status === -1) {
        //     //     const appStore = useAuthStoreHook();
        //     //     appStore.refreshToken().then(() => {
        //     //         location.reload();
        //     //     });
        //     // }
        // }
        return Promise.reject(error.message);
    }
);

// 导出 axios 实例
export default service;

